package vip.liux.front.infrastructure.utils;


import jakarta.websocket.Session;
import org.slf4j.Logger;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import static org.slf4j.LoggerFactory.getLogger;

public class WebSocketManager {

    private static final Logger logger = getLogger(WebSocketManager.class);
    private final static CopyOnWriteArraySet<WebSocketServer> webSocketServerSet = new CopyOnWriteArraySet<>();

    private final static ConcurrentHashMap<String, WebSocketServer> webSocketServerMap = new ConcurrentHashMap<>();

    public static void addWebSocketServer(WebSocketServer webSocketServer) {
        if (webSocketServer != null) {
            webSocketServerSet.add(webSocketServer);
            webSocketServerMap.put(webSocketServer.getSessionId(), webSocketServer);
        }
    }

    public static void removeWebSocketServer(WebSocketServer webSocketServer) {
        webSocketServerSet.remove(webSocketServer);
        webSocketServerMap.remove(webSocketServer.getSessionId());
    }

    /**
     * 通过SessionId发送消息给特定用户
     *
     * @param sessionId 用户SessionId
     * @param message       消息
     */
    public static void sentToUser(String sessionId, String message) {
        Session session = webSocketServerMap.get(sessionId).getSession();
        sentToUser(session, message);
    }

    /**
     * 通过Session发送消息给特定用户
     *
     * @param session 用户Session
     * @param message     消息
     */
    public static void sentToUser(Session session, String message) {
        if (session == null) {
            logger.error("不存在该Session，无法发送消息");
            return;
        }
        session.getAsyncRemote().sendText(message);
    }

    /**
     * 发送消息给所有用户
     *
     * @param message 消息
     */
    public static void sentToAllUser(String message) {
        for (WebSocketServer webSocketServer : webSocketServerSet) {
            sentToUser(webSocketServer.getSessionId(), message);
        }
        logger.info("向所有用户发送WebSocket消息完毕，消息：{}", message);
    }

    public interface WebSocketServer {
        String getSessionId();

        Session getSession();
    }
}